package com.neusoft.hifly.commons.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.neusoft.hifly.core.log.Log;

public class Aes {
	// 密钥16位
	private final static String secretKey = "abcdefgabcdefg12";

	public static void main(final String[] args) throws Exception {
		final String encryptPassword = Aes.encrypt("CTSJ@2020");
		System.out.println("解密前：" + encryptPassword);
		final String decryptPassword = Aes.decrypt(encryptPassword);
		System.out.println("解密后：" + decryptPassword);
	}

	/**
	 * 加密
	 */
	public static String encrypt(final String sSrc) {
		try {
			// 判断Key是否为16位
			if (Aes.secretKey.length() != 16) {
				System.out.print("Key长度不是16位");
				return null;
			}
			final byte[] raw = Aes.secretKey.getBytes("utf-8");
			final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
			final IvParameterSpec iv = new IvParameterSpec(Aes.secretKey.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			final byte[] encrypted = cipher.doFinal(sSrc.getBytes());
			return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
		} catch (final Exception e) {
			Log.error("登录密码解密失败：" + sSrc);
			return sSrc;
		}
	}

	/**
	 * 解密
	 */
	public static String decrypt(String sSrc) {
		sSrc = sSrc.replaceAll(" ", "+");
		try {
			// 判断Key是否为16位
			if (Aes.secretKey.length() != 16) {
				System.out.print("Key长度不是16位");
				return null;
			}
			final byte[] raw = Aes.secretKey.getBytes("utf-8");
			final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			final IvParameterSpec iv = new IvParameterSpec(Aes.secretKey.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			final byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
			try {
				final byte[] original = cipher.doFinal(encrypted1);
				final String originalString = new String(original, "utf-8");
				return originalString;
			} catch (final Exception e) {
				System.out.println(e.toString());
				return null;
			}
		} catch (final Exception ex) {
			Log.error("登录密码解密失败：" + sSrc);
			return sSrc;
		}
	}

}